<template>
    <div class="iconfont">
        <!-- grid layout -->

        <div class="row">
            <div class="col"></div>
            <div :data-error="error.account" :class="{addMsg: error.account !=''}" class="col-9">
                <div class="input-group mb-3">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="basic-addon1">邮箱</span>
                </div>
                <input type="text" class="form-control account-input" 
                v-model="reg.account"
                placeholder="邮箱地址" aria-label="Username" aria-describedby="basic-addon1">
                </div>
            </div>
            <div class="col"></div>
        </div>
        <div class="row">
            <div class="col"></div>
            <div :data-error="error.password" :class="{addMsg: error.password != ''}" class="col-9">
                <div class="input-group mb-3">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="basic-addon1">密码</span>
                </div>
                <input type="password" class="form-control password-input" 
                v-model="reg.password"
                placeholder="注册密码" aria-label="Username" aria-describedby="basic-addon1">
                </div>
            </div>
            <div class="col"></div>
        </div>
        <div v-if="verify" class="row">
            <div class="col"></div>
            <div :data-error="error.vericode" class="col-9" :class="{addMsg: error.vericode != ''}">
                <div class="input-group mb-3 " >
                <input type="text" class="form-control vericode " 
                v-model="reg.vericode" :maxlength="4"
                placeholder="验证码" aria-label="verification-code" aria-describedby="img-verification">
                <div class="input-group-append">
                    <img :src="verify.dataURL" :alt="verify.code"
                        @click="freshCode"
                    >
                </div>
                </div>
            </div>
            <div class="col"></div>
        </div>
        <!-- <div v-else class="row">
            <div class="col"></div>
            <div class="col-9">

            </div>
            <div class="col"></div>
        </div> -->
        <div class="row">
            <div class="col"></div>
            <div class="col-7">
                <button type="button" class="btn btn-primary btn-sm btn-block"
                @click="registerAccount"
                >注册</button>
            </div>
            <div class="col"></div>
        </div>        

    </div>
</template>

<script>
import Verification from 'self-verification-code';
import { regnewAccount } from "../../../api/register.js";
import { getPublickey } from "../../../api/homePage.js";
import cryptico from "cryptico-js";

export default {
    data(){
        return {
            verify: null,
            reg:{
                account: "",
                password:"",
                vericode:""
            },
            error:{
                vericode:"",
                account:"",
                password:""
            },
            fatherPoint: null
        };
    },
    inject:["thisOfToast"],
    mounted(){
        this.fatherPoint = this.thisOfToast();  //弹层组件的指针
        let ver = Verification.CreateImgCode(); //生成验证码
        this.verify = ver;
        
    },
    methods:{
        //刷新验证码
        freshCode(){
            let ver = Verification.CreateImgCode(); //生成验证码
            this.verify = ver;
        },
        async registerAccount(){
            this.resetErrorMsg();
            //错误处理
            let HttpError = (await import("../../../api/error.js")).HttpError;
            // console.log(HttpError);
            let that = this;
            // this.fatherPoint.statusLoading( true );
            if( !this.checkVerificationCode( this.reg.vericode.toLowerCase() ) ){
                //检查验证码 
                // this.$(".password-input").focus();
                this.$(".vericode").focus();
                this.error.vericode = "验证码不正确，请重新输入！";
                return ;
            }

            if(  !(await this.checkEmailFormula(this.reg.account)) ){
                //帐号检查
                this.$(".account-input").focus();
                this.error.account = "邮箱格式错误，请重新输入！";
                return ;
            }

            if(  !(await this.checkPassWord(this.reg.password)) ){
                //帐号密码
                this.$(".password-input").focus();
                this.error.password = "密码格式错误，请重新输入！";
                return ;
            }

            //获取公钥
            await this.publickey();

            //加密 
            let pwd = this.encryptPassword(this.reg.password);
            if(pwd.status = "success"){
                pwd = pwd.cipher;
            }else{
                return ;
            }
            
            
            regnewAccount({
                account : this.reg.account,
                password: pwd
            }).then( res=>{
                console.log("success: ", res);
                this.fatherPoint.type = 'resultOfRegister';
                this.fatherPoint.msg = res.data.msg;
            }).catch( error=>{
                if (error.response) {
                // The request was made and the server responded with a status code
                // that falls out of the range of 2xx
                // console.log(error.response.data);
                // console.log(error.response.status);
                // console.log(error.response.headers);

                
                let err = new HttpError();

                    err.checkResStatus(error.response.data , function(){
                        return that.error;
                    }, that);

                } else if (error.request) {
                // The request was made but no response was received
                // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
                // http.ClientRequest in node.js
                // console.log(error.request);
                } else {
                // Something happened in setting up the request that triggered an Error
                // console.log('Error', error.message);
                }
                // console.log(error.config);
            });

            that.fatherPoint.statusLoading( false );
            // if( res ){
            //     if(res.code == ){

            //     }
            // }
            // setTimeout(function(){
            //     that.fatherPoint.statusLoading( false );
            //     that = null;
            // }, 1000);

        },
        checkVerificationCode( code ){
            if( this.verify.code === code ) return true;
            return false;
        },
        resetErrorMsg(){
            this.error.vericode="",
            this.error.account="",
            this.error.password="";
        },
        async checkEmailFormula( val ){
            let C_v = (await import("../../../api/validate.js")).Validate;
            let v = new C_v();
            return v.checkEmail( val );
        },
        async checkPassWord( val ){
            let C_v = (await import("../../../api/validate.js")).Validate;
            let v = new C_v();
            return v.checkPasswordEmpty( val );
        },
        async publickey(){
            let that = this;
            let key = this.$store.getters.getPublicKey;
            if( key == "" ){
                //从服务端获取key值
                
                // getPublickey().then(function(res){
                //     that.$store.commit("setPublicKey", res.data.key);
                //     that = null;
                // }).catch(function(err){
                //     console.log(err);
                // });

                try{
                    let res = await getPublickey();
                   
                    if(res.code == 0 ){
                        that.$store.commit("setPublicKey", res.data.key);
                        that = null;
                        return ;
                    }
                }catch(err){
                    console.log(err);
                }
            }
            
            
        },
        encryptPassword(val){
            let enkey = cryptico.encrypt(val , this.$store.getters.getPublicKey)
            return enkey;
        }

    }
}
</script>

<style lang="scss">

.addMsg{
    display: flex;
    flex-direction: column;
}
.addMsg::after{
    content: "\e605"" "attr(data-error);
    text-align: left;
    padding: .375rem .75rem .375rem 0;
    margin-top: -.9rem;
    color: red;
}

</style>